import base64

from PyQt6.QtWidgets import QTextEdit, QPushButton, QHBoxLayout, QVBoxLayout

from utils.reference import AbstractCustomDialog, copy_to_clipboard, qt_connect


class DialogBase64(AbstractCustomDialog):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('Base64')

        self.edit_origin_text = QTextEdit(self)
        self.edit_encode_text = QTextEdit(self)

        self.btn_o_to_e = QPushButton('↓', self)
        qt_connect(self.btn_o_to_e.clicked, self.o_to_e)

        self.btn_e_to_o = QPushButton('↑', self)
        qt_connect(self.btn_e_to_o.clicked, self.e_to_o)

        self.btn_copy_o = QPushButton('↑ 复制', self)
        qt_connect(self.btn_copy_o.clicked, self.copy_o)
        self.btn_copy_e = QPushButton('↓ 复制', self)
        qt_connect(self.btn_copy_e.clicked, self.copy_e)

        hbox = QHBoxLayout()
        hbox.addWidget(self.btn_copy_o)
        hbox.addWidget(self.btn_o_to_e)
        hbox.addWidget(self.btn_e_to_o)
        hbox.addWidget(self.btn_copy_e)

        vbox = QVBoxLayout()
        vbox.addWidget(self.edit_origin_text)
        vbox.addLayout(hbox)
        vbox.addWidget(self.edit_encode_text)

        self.setLayout(vbox)

    def o_to_e(self):
        if text := self.edit_origin_text.toPlainText():
            result = base64.b64encode(text.encode()).decode()
            self.edit_encode_text.setPlainText(result)

    def e_to_o(self):
        if text := self.edit_encode_text.toPlainText():
            result = base64.b64decode(text.encode()).decode()
            self.edit_origin_text.setPlainText(result)

    def copy_e(self):
        if text := self.edit_encode_text.toPlainText():
            copy_to_clipboard(text)

    def copy_o(self):
        if text := self.edit_origin_text.toPlainText():
            copy_to_clipboard(text)
